//
//  CityViewController.m
//  XRSquare
//
//  Created by UaenaMo on 2018/8/16.
//  Copyright © 2018年 UaenaMo. All rights reserved.
//

#import "CityViewController.h"
#import "CityTopTableViewCell.h"
#import "CityTableViewCell.h"
#import "DistrictViewController.h"

@interface CityViewController ()<UITableViewDelegate,UITableViewDataSource,UITextFieldDelegate,distr,CityTopTableViewCellDelegate>
{
    UITableView * tableView;
    UITableView * resultTableView;
    UITextField * searchTextField;
    NSDictionary * cityDic;
    NSMutableArray * searchArr;
    
    NSString * geoCurrentCity;
    
    NSString * currentProvs;
    NSString * currentcitys;
}

@end

@implementation CityViewController

-(instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    if (self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil])
    {
        self.showTop = NO;
    }
    return self;
}

-(void)backAction
{
    if (!resultTableView.hidden && resultTableView)
    {
        resultTableView.hidden = YES;
    }
    else
    {
        [self.navigationController popViewControllerAnimated:YES];
    }
}

- (void)viewDidLoad
{
    
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.navigationController.navigationBar.hidden = NO;
    self.view.backgroundColor = [UIColor whiteColor];
    self.navigationController.navigationBar.tintColor = [UIColor grayColor];
    
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[[UIImage imageNamed:@"back"] imageWithRenderingMode:UIImageRenderingModeAlwaysTemplate] style:UIBarButtonItemStylePlain target:self action:@selector(backAction)];
    
    CGRect rectStatus = [[UIApplication sharedApplication] statusBarFrame];
    CGRect rectNav = self.navigationController.navigationBar.frame;
    
    self.title = @"选择城市";
    
    tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, rectNav.size.height + rectStatus.size.height, ScreenWidth, ScreenHeight - rectStatus.size.height - rectNav.size.height) style:UITableViewStylePlain];
    tableView.delegate = self;
    tableView.dataSource = self;
    tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self.view addSubview:tableView];
    
    if (self.showTop) {
        UIView * searchView = [[UIView alloc]initWithFrame:CGRectMake(60, 20, ScreenWidth - 70, 30)];
        searchView.backgroundColor = [UIColor colorFromHexCode:@"f3f3f3"];
        searchView.layer.cornerRadius = 15;
        
        searchTextField = [[UITextField alloc]initWithFrame:CGRectMake(10, 0, ScreenWidth - 70 - 20, 30)];
        searchTextField.placeholder = @"输入地名以搜索";
        searchTextField.delegate = self;
        searchTextField.returnKeyType = UIReturnKeySearch;
        [searchView addSubview:searchTextField];
        
        self.navigationItem.titleView = searchView;
        
        resultTableView = [[UITableView alloc]initWithFrame:CGRectMake(0, rectNav.size.height + rectStatus.size.height, ScreenWidth, ScreenHeight - rectStatus.size.height - rectNav.size.height) style:UITableViewStylePlain];
        resultTableView.delegate = self;
        resultTableView.dataSource = self;
        resultTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        [self.view addSubview:resultTableView];
        resultTableView.hidden = YES;
    }
    
    [self requestData];
}

-(BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [self search];
    [textField resignFirstResponder];
    return YES;
}

-(void)search
{
    searchArr = [NSMutableArray array];
    for (NSString * key in cityDic.allKeys)
    {
        for (NSDictionary * dic in [cityDic objectForKey:key])
        {
            if ([[dic objectForKey:@"CityName"]containsString:searchTextField.text] || [[dic objectForKey:@"CityName"]isEqualToString:searchTextField.text])
            {
                [searchArr addObject:dic];
            }
        }
    }
    resultTableView.hidden = NO;
    [resultTableView reloadData];
}

-(void)requestData
{
    [NetRequestCenter citylistResult:^(BOOL success, NSDictionary *resultDic) {
        if (success) {
            cityDic = [resultDic objectForKey:@"data"];
            [tableView reloadData];
        }
    }];
}

#pragma mark - tableview

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    if (tableView == resultTableView)
    {
        return 1;
    }
    else
    {
        if (self.showTop)
        {
            return [[cityDic allKeys] count] + 1;
        }
        else
        {
            return [[cityDic allKeys]count];
        }
    }
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    if (tableView == resultTableView)
    {
        return 0;
    }
    else
    {
        if (self.showTop)
        {
            if (section == 0)
            {
                return 0;
            }
            else
            {
                return 30;
            }
        }
        else
        {
            return 30;
        }
    }
}

-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    if (tableView == resultTableView)
    {
        return [UIView new];
    }
    else
    {
        if (self.showTop)
        {
            if (section == 0)
            {
                return [[UIView alloc]init];
            }
            else
            {
                UIView * header = [[UIView alloc]initWithFrame:CGRectMake(0, 0, ScreenWidth, 30)];
                header.backgroundColor = [UIColor colorFromHexCode:@"f3f3f3"];
                
                UILabel * label = [[UILabel alloc]initWithFrame:CGRectMake(10, 0, ScreenWidth, 30)];
                label.font = [UIFont boldSystemFontOfSize:15];
                label.textColor = themeColor;
                label.text = [NSString stringWithFormat:@"%c",(char)('A' + section - 1)];
                [header addSubview:label];
                return header;
            }
        }
        else
        {
            UIView * header = [[UIView alloc]initWithFrame:CGRectMake(0, 0, ScreenWidth, 30)];
            header.backgroundColor = [UIColor colorFromHexCode:@"f3f3f3"];
            
            UILabel * label = [[UILabel alloc]initWithFrame:CGRectMake(10, 0, ScreenWidth, 30)];
            label.font = [UIFont boldSystemFontOfSize:15];
            label.textColor = themeColor;
            label.text = [NSString stringWithFormat:@"%c",(char)('A' + section)];
            [header addSubview:label];
            return header;
        }
    }
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (tableView == resultTableView)
    {
        return [searchArr count];
    }
    else
    {
        if (self.showTop)
        {
            if (section == 0)
            {
                return 1;
            }
            else
            {
                return [[cityDic objectForKey:[NSString stringWithFormat:@"%c",(char)('A' + section - 1)]]count];
            }
        }
        else
        {
            return [[cityDic objectForKey:[NSString stringWithFormat:@"%c",(char)('A' + section)]]count];
        }
    }
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (tableView == resultTableView)
    {
        return  [CityTableViewCell height];
    }
    else
    {
        if (self.showTop) {
            if (indexPath.section == 0)
            {
                return [CityTopTableViewCell height];
            }
            else
            {
                return [CityTableViewCell height];
            }
        }
        else
        {
            return [CityTableViewCell height];
        }
    }
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (tableView == resultTableView)
    {
        static NSString * identifer = @"22";
        CityTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:identifer];
        if (!cell) {
            cell = [[CityTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifer];
        }
        [cell loadData:[[searchArr objectAtIndex:indexPath.row]objectForKey:@"CityName"]];
        return cell;
    }
    else
    {
        if (self.showTop) {
            if (indexPath.section == 0) {
                static NSString * identifer = @"top";
                CityTopTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:identifer];
                if (!cell) {
                    cell = [[CityTopTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifer];
                }
                cell.delegate = self;
                [cell loadData:self.selectCity];
                return cell;
            }
            else
            {
                static NSString * identifer = @"en";
                CityTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:identifer];
                if (!cell) {
                    cell = [[CityTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifer];
                }
                NSDictionary * citydddd = [[cityDic objectForKey:[NSString stringWithFormat:@"%c",(char)('A' + indexPath.section - 1)]]objectAtIndex:indexPath.row];
                [cell loadData:[citydddd objectForKey:@"CityName"]];
                return cell;
            }
        }
        else
        {
            static NSString * identifer = @"en";
            CityTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:identifer];
            if (!cell) {
                cell = [[CityTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifer];
            }
            NSDictionary * citydddd = [[cityDic objectForKey:[NSString stringWithFormat:@"%c",(char)('A' + indexPath.section)]]objectAtIndex:indexPath.row];
            [cell loadData:[citydddd objectForKey:@"CityName"]];
            return cell;
        }
    }
}

-(BOOL)tableView:(UITableView *)tableView shouldHighlightRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (tableView == resultTableView)
    {
        return YES;
    }
    else
    {
        if (self.showTop) {
            if (indexPath.section == 0)
            {
                return NO;
            }
            else
            {
                return YES;
            }
        }
        else
        {
            return YES;
        }
    }
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];

    if (tableView != resultTableView)
    {
        NSDictionary * citydddd;
        if (self.showTop)
        {
            citydddd = [[cityDic objectForKey:[NSString stringWithFormat:@"%c",(char)('A' + indexPath.section - 1)]]objectAtIndex:indexPath.row];
        }
        else
        {
            citydddd = [[cityDic objectForKey:[NSString stringWithFormat:@"%c",(char)('A' + indexPath.section)]]objectAtIndex:indexPath.row];
        }
        
        currentcitys = [citydddd objectForKey:@"CityName"];
        currentProvs = [citydddd objectForKey:@"ProvinceName"];
        
        if (self.citySA)
        {
            [self.delegate city:currentcitys province:currentProvs code:[citydddd objectForKey:@"CityId"]];
            [self.navigationController popViewControllerAnimated:YES];
        }
        else
        {
            DistrictViewController * district = [[DistrictViewController alloc]init];
            district.cityId = [citydddd objectForKey:@"CityId"];
            district.delegate = self;
            [self.navigationController pushViewController:district animated:YES];
        }
    }
    else
    {
        NSDictionary * citydddd;
        
        citydddd = [searchArr objectAtIndex:indexPath.row];
        
        currentcitys = [citydddd objectForKey:@"CityName"];
        currentProvs = [citydddd objectForKey:@"ProvinceName"];
        
        if (self.citySA)
        {
            [self.delegate city:currentcitys province:currentProvs code:[citydddd objectForKey:@"CityId"]];
            [self.navigationController popViewControllerAnimated:YES];
        }
        else
        {
            DistrictViewController * district = [[DistrictViewController alloc]init];
            district.cityId = [citydddd objectForKey:@"CityId"];
            district.delegate = self;
            [self.navigationController pushViewController:district animated:YES];
        }
    }
   
}

- (NSArray *) sectionIndexTitlesForTableView:(UITableView *)tableView
{
    NSMutableArray * arr = [NSMutableArray array];
    
    if (tableView == resultTableView)
    {
    }
    else
    {
        if (self.showTop)
        {
            [arr addObject:@"当前"];
            [arr addObjectsFromArray:[self sortArr:[cityDic allKeys]]];
        }
        else
        {
            [arr addObjectsFromArray:[self sortArr:[cityDic allKeys]]];
        }
    }
    return arr;
}

-(NSArray *)sortArr:(NSArray *)arr
{
    if (![arr count]) {
        return @[];
    }
    NSMutableArray * resultArr = [NSMutableArray arrayWithArray:arr];
    
    for ( int i = 0; i < [resultArr count] - 1; i ++)
    {
        for (int j = 0; j < [resultArr count] - 1 - i; j ++)
        {
            if ([[resultArr objectAtIndex:j]compare:[resultArr objectAtIndex:(j + 1)] options:NSCaseInsensitiveSearch] == NSOrderedDescending)
            {
                NSString * content = [resultArr objectAtIndex:j];
                [resultArr replaceObjectAtIndex:j withObject:[resultArr objectAtIndex:(j + 1)]];
                [resultArr replaceObjectAtIndex:(j + 1) withObject:content];
            }
        }
    }
    return resultArr;
}

-(NSInteger)tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index
{
    NSLog(@"%ld,,,%@",index,title);
    return index;
    
}

-(void)selectedDis:(NSString *)dis disid:(NSString *)disid city:(NSString *)city
{
    [self.delegate city:currentcitys province:currentProvs dis:dis code:disid cityCode:city];
    [self.navigationController popViewControllerAnimated:YES];
}

-(void)geoLocaitonAction
{
    NSString * currCity = [[NSUserDefaults standardUserDefaults]objectForKey:@"geocity"];
    [NetRequestCenter CITYset:currCity result:^(BOOL success, NSDictionary *resultDic) {
        [self backAction];
        if (success) {
        }
    }];
}

-(void)selectLocaittonAction
{
    [self backAction];
}

    
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
